﻿using B.S.AuthCenter.Api.Read.Application.Command.Approval;
using B.S.AuthCenter.Api.Read.DTOs.Approval;
using B.S.AuthCenter.Domain.Approval;
using B.S.AuthCenter.Domain.Form;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.AuthCenter.Api.Read.Application.Handler.Approval
{
    public class GetScheduleHandler : IRequestHandler<GetScheduleCommand, ApiResult<ScheduleDTO>>
    {
        IBaseRepository<AppFormModel> appRepo;

        public GetScheduleHandler(IBaseRepository<AppFormModel> appRepo)
        {
            this.appRepo = appRepo;
        }

        public Task<ApiResult<ScheduleDTO>> Handle(GetScheduleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ScheduleDTO> res = new ApiResult<ScheduleDTO>();
           
            var query = appRepo.GetAll().Where(c => !c.IsDeleted && c.State==0).Select(x => new
            {
               x.AppName,
               x.StartTime,
               x.EndTime,
               x.TotalTime,
                
            }).ToList();
            if (!string.IsNullOrEmpty(request.SName))
            {
                query = query.Where(c => c.AppName.Contains(request.SName)).ToList();
            }

            var result = new Dictionary<string, int[]>();
            foreach (var item in query)
            {
                if(!result.ContainsKey(item.AppName))
                {
                    result[item.AppName] = new int[12];
                }
                var currentDate = item.StartTime;
                var endDate = item.EndTime;
                var workStartTime = 9; // 工作开始时间（小时）
                var workEndTime = 17;  // 工作结束时间（小时）

                while (currentDate <= endDate)
                {
                    var monthIndex = currentDate.Month - 1;
                    var dailyHours = 0;

                    // 计算当天的工作时间段
                    var dayWorkStart = new DateTime(
                        currentDate.Year,
                        currentDate.Month,
                        currentDate.Day,
                        workStartTime, 0, 0
                    );
                    var dayWorkEnd = new DateTime(
                        currentDate.Year,
                        currentDate.Month,
                        currentDate.Day,
                        workEndTime, 0, 0
                    );

                    // 计算当天的请假工时
                    if (currentDate.Date == item.StartTime.Date)
                    {
                        // 开始日期：计算StartTime到当天工作结束时间(17:00)的请假工时
                        var start = item.StartTime;
                        var end = dayWorkEnd;
                        if (start < end)
                        {
                            dailyHours = Math.Min(8, (int)(end - start).TotalHours);
                        }
                    }
                    else if (currentDate.Date == endDate.Date)
                    {
                        // 结束日期：计算当天工作开始时间(9:00)到EndTime的请假工时
                        var start = dayWorkStart;
                        var end = item.EndTime;
                        if (start < end)
                        {
                            dailyHours = Math.Min(8, (int)(end - start).TotalHours);
                        }
                    }
                    else
                    {
                        // 中间日期：如果有全天请假，计算8小时
                        dailyHours = 8;
                    }

                    result[item.AppName][monthIndex] += dailyHours;
                    currentDate = currentDate.AddDays(1);
                    currentDate = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 0, 0, 0);
                }
            }
           var dto=  new ScheduleDTO
            {
                EmployeeLeaveData = result,
            };
            res.Msg = "成功";
            res.Code=ApiEnum.Success;
            res.Datas = dto;
           return Task.FromResult(res);
        }
    }
}
